package com.javaking.clanteam.studentutils;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;

public class HorizontalDivider extends View {
	private int mDividerColor;

	public HorizontalDivider(Context context) {
		super(context);
		init(null, 0);
	}

	public HorizontalDivider(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(attrs, 0);
	}

	public HorizontalDivider(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(attrs, defStyle);
	}

	private void init(AttributeSet attrs, int defStyle) {
		// Load attributes
		final TypedArray a = getContext().obtainStyledAttributes(attrs,
				R.styleable.HorizontalDivider, defStyle, 0);
		
		if (!(a.hasValue(R.styleable.HorizontalDivider_color))) {
			throw new IllegalArgumentException("HorizontalDivider must specify a color");
		}
		
		mDividerColor = a.getColor(R.styleable.HorizontalDivider_color, 0);
		
		a.recycle();
		
		// Update TextPaint and text measurements from attributes
		invalidate();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		// TODO: consider storing these as member variables to reduce
		// allocations per draw cycle.
		int paddingLeft = getPaddingLeft();
		int paddingTop = getPaddingTop();
		int paddingRight = getPaddingRight();
		int paddingBottom = getPaddingBottom();

		int contentWidth = getWidth() - paddingLeft - paddingRight;
		int contentHeight = getHeight() - paddingTop - paddingBottom;

		canvas.drawBitmap(makeGradient(mDividerColor, contentHeight, contentWidth),
				paddingLeft,paddingTop,null);
	}
	
	private static Bitmap makeGradient(int color, int height, int width) {
		LinearGradient grad = new LinearGradient(0, height/2, width/2, height/2,
				0, color, Shader.TileMode.REPEAT);
		Paint p = new Paint();
		p.setDither(true);
		p.setShader(grad);
		p.setColor(color);
		p.setStyle(Paint.Style.FILL_AND_STROKE);
	
		Bitmap gradient = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
		Canvas c = new Canvas(gradient);
		Rect rect = new Rect(0,0,width/2,width/2);
		c.drawRect(rect, p);
		c.scale(-1, 1, width/2, 0);
		c.drawRect(rect, p);
		c.drawLine(width/2, 0, width/2, height, p);
		return gradient;
	}


	/**
	 * Gets the example color attribute value.
	 * 
	 * @return The example color attribute value.
	 */
	public int getDividerColor() {
		return mDividerColor;
	}

	/**
	 * Sets the view's example color attribute value. In the example view, this
	 * color is the font color.
	 * 
	 * @param exampleColor
	 *            The example color attribute value to use.
	 */
	public void setDividerColor(int color) {
		mDividerColor = color;
		invalidate();
	}

}
